const qiniu = require('qiniu');

class QN {
    constructor() {
        this.AK = 'PZTGMGFmJKAvxloX1tI4HBmgZH9gde4qqkQshI2V',
        this.SK = 'B2nLYJeTyZfZgklMgRXp1dLgtAdv4-l1nLQ8NvBk';
        this.BK = 'car-room';
        this.name = '';
        let mac = new qiniu.auth.digest.Mac(this.AK, this.SK);//鉴权
        
        let op = {
            bucket: this.BK + ":" + keyToOverwrite,
            expires: 7200,
            returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
        };

        let putPolicy = new qiniu.rs.PutPolicy(op);

        let conf = new qiniu.conf.Config();
        conf.zone = qiniu.zone.Zone_z2;
        
        this.uploadToken = putPolicy.uploadToken(mac);//上传凭证
        this.formUploader = new qiniu.form_up.FormUploader(conf);
        this.putExtra = new qiniu.form_up.PutExtra();
        this.bucketManager = new qiniu.rs.BucketManager(mac, conf);

        setInterval(() => {
            let token = putPolicy.uploadToken(mac);
            this.uploadToken = token;
        }, 7000*1000);
    }
    uploadFile(path, rename) {
        return new Promise((resolve, reject) => {
            this.formUploader.put(this.uploadToken, rename, path, this.putExtra, (err, body, info) => {
                if(err) {
                    reject(err);
                }
                if(info.statusCode == 200) {
                    resolve(body)
                }else {
                    reject(info.statusCode)
                }
            })
        })
    }
    deleteFile(name) {
        return new Promise((resolve, reject) => {
            this.bucketManager.delete(this.BK, name, (err, body, info) => {
                if(err) {
                    reject(err)
                }else {
                    resolve(body);
                }
            })
        })
    }
}

module.exports = new QN();